package com.lzq.chatroom_project.model;

import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class SensitiveWordTrie {
    private final TrieNode root = new TrieNode();

    // Trie 树节点
    private static class TrieNode {
        Map<Character, TrieNode> children = new HashMap<>();
        boolean isEndOfWord = false;
    }

    // 添加敏感词
    public void addWord(String word) {
        TrieNode current = root;
        for (char c : word.toCharArray()) {
            current = current.children.computeIfAbsent(c, k -> new TrieNode());
        }
        current.isEndOfWord = true;
    }

    // 过滤敏感词
    public String filter(String message) {
        StringBuilder result = new StringBuilder();
        TrieNode current;
        for (int i = 0; i < message.length(); i++) {
            current = root;
            int j = i;
            boolean found = false;
            while (j < message.length() && current.children.containsKey(message.charAt(j))) {
                current = current.children.get(message.charAt(j));
                if (current.isEndOfWord) {
                    result.append("***");
                    i = j;
                    found = true;
                    break;
                }
                j++;
            }
            if (!found) {
                result.append(message.charAt(i));
            }
        }
        return result.toString();
    }

    public void buildSensitiveTree(List<String> words) {
        words.forEach(this::addWord);
    }
}
